
<template>
<div class="pictureDetailPage">
  <a-row :gutter="[16, 16]">
    <!-- 图片展示区 -->
    <a-col :sm="24" :md="16" :xl="18">
      <a-card title="图片预览">
        <a-image
          style="max-height: 600px; object-fit: contain"
          :src="picture.url"
        />
      </a-card>
    </a-col>
    <!-- 图片信息区 -->
    <a-col :sm="24" :md="8" :xl="6">
      <a-card title="图片信息">
        <a-descriptions :column="1">
          <a-descriptions-item label="作者">
            <a-space>
              <a-avatar :size="24" :src="picture.user?.userAvatar" />
              <div>{{ picture.user?.userName }}</div>
            </a-space>
          </a-descriptions-item>
          <a-descriptions-item label="名称">
            {{ picture.name ?? '未命名' }}
          </a-descriptions-item>
          <a-descriptions-item label="简介">
            {{ picture.introduction ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="分类">
            {{ picture.category ?? '默认' }}
          </a-descriptions-item>
          <a-descriptions-item label="标签">
            <a-tag v-for="tag in picture.tags" :key="tag">
              {{ tag }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="格式">
            {{ picture.picFormat ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="宽度">
            {{ picture.picWidth ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="高度">
            {{ picture.picHeight ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="宽高比">
            {{ picture.picScale ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="大小">
            {{ formatSize(picture.picSize) }}
          </a-descriptions-item>
          <a-descriptions-item label="主色调">
            <a-space>
              {{ picture.picColor ?? '-' }}
              <div
                v-if="picture.picColor"
                :style="{
        backgroundColor: toHexColor(picture.picColor),
        width: '16px',
        height: '16px',
      }"
              />
            </a-space>
          </a-descriptions-item>
          <a-space wrap>
            <a-button type="primary" @click="doDownload">
              免费下载
              <template #icon>
                <DownloadOutlined />
              </template>
            </a-button>
            <a-button  type="primary" ghost  @click="doShare">
              <ShareModal ref="shareModalRef" :link="shareLink" />
              <template #icon>
             <ShareAltOutlined />
              </template>
              分享
            </a-button>

          </a-space>
          <a-space>
            <a-button v-if="canEdit" type="default" @click="doEdit">
              编辑
              <template #icon>
                <EditOutlined />
              </template>
            </a-button>
            <a-button v-if="canDelete" danger @click="doDelete">
              删除
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>


          </a-space>
        </a-descriptions>
      </a-card>
    </a-col>
  </a-row>

  <!-- 评论区 -->
  <PictureComment :pictureId="(picture.id)" />
</div>
</template>
<script setup lang="ts">

import ShareModal from '@/components/ShareModal.vue'
import PictureComment from '@/components/PictureComment.vue'
import { computed, h, onMounted, ref } from 'vue'
import {
  deletePictureUsingPost,
  doPictureReviewUsingPost,
  getPictureVoByIdUsingGet
} from '@/api/pictureController.ts'
import { message, Modal } from 'ant-design-vue'
import { downloadImage, formatSize, toHexColor } from '../utils'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import router from '@/router'
import {
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined,
  ShareAltOutlined
} from '@ant-design/icons-vue'
import { PIC_REVIEW_STATUS_ENUM } from '@/constants/picture.ts'
import { SPACE_PERMISSION_ENUM } from '@/constants/space.ts' // 引入图标组件


/*由于图片详情页要展示的图片是根据 id 而变化的，所以此处使用动态路由。在页面中可以使用 props 获取到动态的参数*/
const props = defineProps<{
  id: string | number
}>()



/*然后就可以在页面加载时，通过 id 调用接口来获取到图片*/
const picture = ref<API.PictureVO>({})

// 获取图片详情
const fetchPictureDetail = async () => {
  try {
    const res = await getPictureVoByIdUsingGet({
      id: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
    } else {
      message.error('获取图片详情失败，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取图片详情失败：' + e.message)
  }
}

onMounted(() => {
  fetchPictureDetail()
})



/*编写权限判断逻辑，canEdit 的值为 true 表示有编辑和删除权限*/
const loginUserStore = useLoginUserStore()
// // 是否具有编辑权限（更新为框架检查）
// const canEdit = computed(() => {
//   const loginUser = loginUserStore.loginUser;
//   // 未登录不可编辑
//   if (!loginUser.id) {
//     return false
//   }
//   // 仅本人或管理员可编辑
//   const user = picture.value.user || {}
//   return loginUser.id === user.id || loginUser.userRole === 'admin'
// })





// 编辑
const doEdit = () => {
  router.push({
    path: '/add_picture',
    query: {
      id: picture.value.id,
      spaceId: picture.value.spaceId
    }
  })
}

// 删除


const doDelete = async () => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这张图片吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      const id = picture.value.id;
      if (!id) {
        return;
      }
      const res = await deletePictureUsingPost({ id });
      if (res.data.code === 0) {
        message.success('删除成功');
        router.push('/');
      } else {
        message.error('删除失败');
      }
    },
    onCancel: () => {
      message.info('已取消删除');
    },
  });
};




// 处理下载
const doDownload = () => {
  downloadImage(picture.value.url)
}


/*审核函数*/
const handleReview = async (record: API.Picture, reviewStatus: number) => {
  const reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : '管理员操作拒绝'
  const res = await doPictureReviewUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage,
  })
  if (res.data.code === 0) {
    message.success('审核操作成功')

  } else {
    message.error('审核操作失败，' + res.data.message)
  }
}



// 分享弹窗引用
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()

// 分享
const doShare = () => {

  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.value.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}


// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (picture.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canEdit = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDelete = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)

</script>
<style scoped>

</style>
